import { Inject } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { ClassTrainLogEntity } from '../../entity/trainLog';
import { ClassTrainLogService } from '../../service/trainLog';
import { ClassInfoEntity } from '../../entity/info';
import { BaseSysUserEntity } from '../../../base/entity/sys/user';
import { StudentStudentEntity } from '../../../student/entity/student';

/**
 * 训练日志
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: ClassTrainLogEntity,
  service: ClassTrainLogService,
  pageQueryOp: {
    keyWordLikeFields: ['b.nickName', 'c.name'],
    fieldEq: ['a.type', 'a.studentId', 'b.name', 'b.phone', 'c.shopId'],
    select: [
      'a.*',
      'b.name as studentName',
      'b.phone as studentPhone',
      'c.className as className',
      'd.name as operatorName',
      'c.shopId as classShopId'
    ],
    join: [
      {
        entity: StudentStudentEntity,
        alias: 'b',
        condition: 'a.studentId = b.id',
        type: 'leftJoin',
      },
      {
        entity: ClassInfoEntity,
        alias: 'c',
        condition: 'a.classId = c.id',
        type: 'leftJoin',
      },
      {
        entity: BaseSysUserEntity,
        alias: 'd',
        condition: 'a.operatorId = d.id',
        type: 'leftJoin',
      },
    ],
    where: async ctx => {
      const { time, classShopId, studentName, studentPhone } = ctx.request.body;
      const where = [];
      if (time && time.length === 2) {
        where.push([
          'a.createTime BETWEEN :start AND :end',
          { start: time[0], end: time[1] },
        ]);
      }
      if (classShopId) {
        where.push(['c.shopId = :classShopId', { classShopId }]);
      }
      if (studentName) {
        where.push(['b.name LIKE :studentName', { studentName: `%${studentName}%` }]);
      }
      if (studentPhone) {
        where.push(['b.phone LIKE :studentPhone', { studentPhone: `%${studentPhone}%` }]);
      }
      return where;
    },
  },
  insertParam: ctx => {
    return {
      operatorId: ctx.admin.userId,
    };
  },
})
export class AdminClassTrainLogController extends BaseController {
  @Inject()
  classTrainLogService: ClassTrainLogService;
}
